import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  DeviceEventEmitter,
  NativeAppEventEmitter
} from 'react-native';

import * as config from '../../constants/apiConfig';
import styles from './hkBindCardStyle';
import DatePicker from 'react-native-datepicker';
import moment from 'moment';
import api from '../../services/api';
import helper from '../util/helper';
import Toast from 'react-native-sk-toast';
import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';
import KeyboardAwareScrollView from '../global/keyboardScrollView/KeyboardAwareScrollView';
import CountDownText from '../global/countDown/CountDownText';
import Touch from '../global/Touch';

class HkBindCard extends Component {
    constructor(props) {
		super(props);

        // let {data, source} = this.props;
		this.state = {
            isLoading: true,
			isRefreshing: false,
            disabled:false
		};
		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    async _sendCode(){
        let { session, old_id } = this.props;

        if(this.state.interval){
            return;
        }

        let {card_phone} = this.state;

        if(!card_phone){
            this.refs.toast.show('请输入银行预留手机号');
            return;
        }

        if(!/^1[0-9]{10}$/.test(card_phone)){
            this.refs.toast.show('请输入正确的银行预留手机号');
            return;
        }

        this.setState({loadingShow: true, interval: true});
        let type = this.props.type == 'CHANGE_CARD' && old_id ? 'CHANGE_BINDCARD' : 'BIND_CARD';
        let res = await api.post("/housekeeper/sendCode",{phone:card_phone,type});
        this.setState({loadingShow: false});

        if(res.cd == 1){
            this.setState({interval:false});
            this.refs.toast.show(res.msg);
            return;
        }

        if(!res.data || res.data.status_code != "OK"){
            this.setState({interval:false});
            if(res.data.status_code == 'isv.BUSINESS_LIMIT_CONTROL'){
                this.refs.toast.show("发送频繁，请稍后重试");
            }else if(res.data.status_code == 'isv.MOBILE_NUMBER_ILLEGAL'){
                this.refs.toast.show("手机号码格式错误");
            }else{
                this.refs.toast.show("发送验证码失败");
            }

			return;
		}

        this.refs.countDownText.start();
        this.refs.toast.show("验证码已发送到您的手机\n10分钟内输入有效", 2000);

        // this.setState({code: res.msg});

        console.log("##", res);
    }

    _addBind(){
        let {navigator} = this.props;
        navigator.push({
            title: "银行列表",
            backButtonTitle:'',
			screen: 'housekeeperapp.bindcardlist',
			passProps: {
				// orderId
			},
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ]
            }
			// backButtonHidden: true,
		});
    }

    _addProvince(){
        let {navigator,card} = this.props;
        if(!card.bank_name){
            this.refs.toast.show('请先输入银行');
            return;
        }

        navigator.push({
            title: "开户行省列表",
            backButtonTitle:'',
			screen: 'housekeeperapp.cardprovincelist',
			passProps: {
				// orderId
			},
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ]
            }
			// backButtonHidden: true,
		});
    }

    _addCity(){
        let {navigator, card} = this.props;
        if(!card.card_province){
            this.refs.toast.show('请先输入开户行省');
            return;
        }

        navigator.push({
            title: "开户行市列表",
            backButtonTitle:'',
			screen: 'housekeeperapp.cardcitylist',
			passProps: {
				// orderId
			},
            navigatorStyle:{
                navBarHidden: false,
                tabBarHidden: true,
                navBarTextColor: 'white',
            	navBarButtonColor: 'white',
            	navBarBackgroundColor: '#EA5404',
                statusBarColor: '#EA5404',
                navBarTitleTextCentered: true,
                topBarElevationShadowEnabled:false
            },
            navigatorButtons: {
                leftButtons:[
                    {
                        id: 'back',
                        icon: require("../../../img/hk_back_icon.png")
                    }
                ]
            }
			// backButtonHidden: true,
		});
    }

    async _submitAction(){
        let {card_name, card_cd, card_no, card_phone, code} = this.state;
        let {card,type,old_id} = this.props; // 更换银行卡的类型 type 和原银行卡id old_id

        if(!card_name){
            this.refs.toast.show('请输入姓名');
            return;
        }
        if(!card_cd){
            this.refs.toast.show('请输入身份证号码');
            return;
        }

        if(!/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(card_cd)){
            this.refs.toast.show('请输入正确的身份证号码');
            return;
        }

        if(!card_no){
            this.refs.toast.show('请输入借记卡号');
            return;
        }

        if(!card.bank_name){
            this.refs.toast.show('请输入所属银行');
            return;
        }
        if(!card.card_province){
            this.refs.toast.show('请输入开户行省');
            return;
        }
        if(!card.card_city){
            this.refs.toast.show('请输入开户行市');
            return;
        }

        if(!card_phone){
            this.refs.toast.show('请输入银行预留手机号');
            return;
        }

        if(!/^1[0-9]{10}$/.test(card_phone)){
            this.refs.toast.show('请输入正确的银行预留手机号');
            return;
        }

        if(!code){
            this.refs.toast.show('请输入验证码');
            return;
        }

        this.setState({loadingShow:true,disabled:true});
        let res;
        if (type == 'CHANGE_CARD' && old_id) {
            // 更换银行卡添加额外的信息
            res = await api.post("/card/changeCard",{...this.state,...card,old_id});
        } else {
            res = await api.post("/card/bind",{...this.state,...card});
        }

        this.setState({loadingShow:false});

        console.log("###", res);
        if(res.cd == 1){
            this.refs.toast.show(res.msg,1000,() =>{
                this.setState({disabled:false})
            });
        }else {
            if(res && res.data=='交易成功'){
                let msg = type == 'CHANGE_CARD' && old_id ? '恭喜您，更换成功' : '恭喜您，添加成功';
                this.refs.toast.show(msg, 2000, ()=>{
                    this.setState({disabled:false})
                    this.props.navigator.pop();
                });
            }else{
                if(res && res.data == "该银行卡bin不支持"){
                    this.refs.toast.show("暂不支持添加该银行卡", 2000);
                }else{
                    this.refs.toast.show(res.data, 2000);
                }
                this.setState({disabled:false})
            }
        }

    }

    componentWillUnmount(){
        let {dispatch, actions} = this.props;

        dispatch(actions.card.card_name_change(''));
        dispatch(actions.card.card_province_change(''));
        dispatch(actions.card.card_city_change(''));
    }

    render() {
        // let {data, source} = this.props;

        return (
            <View style={[styles.wrapper,{backgroundColor:'#f3f3f3'}]}>
                <KeyboardAwareScrollView style={[styles.container,{marginBottom:50}]} extraScrollHeight={60}>
                    <View style={styles.addressContainer}>
                        <View style={styles.formItem}>
                            <Text style={[styles.leftText,{paddingRight:30}]}>姓名</Text>
                            <TextInput
                                value={this.state.card_name}
                                style={styles.itemRight}
                                editable = {true}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入姓名'}
                                placeholderTextColor={'#B5B5B5'}
                                onChangeText={(text)=>{this.setState({card_name:text})}}
                            />
                        </View>
                        <View style={[styles.formItem,{borderBottomWidth:0}]}>
                            <Text style={styles.leftText}>身份证号</Text>
                            <TextInput
                                value={this.state.card_cd}
                                style={styles.itemRight}
                                editable = {true}
                                keyboardType={'numeric'}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入身份证号码'}
                                placeholderTextColor={'#B5B5B5'}
                                onChangeText={(text)=>{this.setState({card_cd:text})}}
                            />
                        </View>
                    </View>

                    <Text style={styles.formTitle}>请添加本人名下的银行卡</Text>

                    <View style={[styles.formContainer,{marginTop:5}]}>
                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>银行卡号</Text>
                            <TextInput
                                value={this.state.card_no}
                                style={styles.itemRight}
                                editable = {true}
                                keyboardType={'numeric'}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                onChangeText={(text)=>{this.setState({card_no:text})}}
                                placeholder={'请输入借记卡号'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        </View>
                        <TouchableOpacity style={[styles.formItem,{marginRight:15}]} onPress={this._addBind.bind(this)}>
                            <Text style={styles.leftText}>所属银行</Text>
                            <TextInput
                                defaultValue={this.props.card.bank_name}
                                style={styles.itemRight}
                                editable = {false}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请选择银行'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                            <Image source={require('../../../img/hk_arrow_icon.png')} style={styles.rightImage}/>
                        </TouchableOpacity>

                        <TouchableOpacity style={[styles.formItem,{marginRight:15}]} onPress={this._addProvince.bind(this)}>
                            <Text style={styles.leftText}>开户行省</Text>
                            <TextInput
                                defaultValue={this.props.card.card_province}
                                style={styles.itemRight}
                                editable = {false}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请选择开户行省'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                            <Image source={require('../../../img/hk_arrow_icon.png')} style={styles.rightImage}/>
                        </TouchableOpacity>
                        <TouchableOpacity style={[styles.formItem,{borderBottomWidth:0,marginRight:15,}]} onPress={this._addCity.bind(this)}>
                            <Text style={styles.leftText}>开户行市</Text>
                            <TextInput
                                defaultValue={this.props.card.card_city}
                                onChangeText={(text)=>{this.setState({remarks:text})}}
                                style={styles.itemRight}
                                editable = {false}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请选择开户行市'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                            <Image source={require('../../../img/hk_arrow_icon.png')} style={styles.rightImage}/>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.addressContainer}>
                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>预留手机</Text>
                            <TextInput
                                value={this.state.card_phone}
                                style={styles.itemRight}
                                editable = {true}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入银行预留手机号'}
                                placeholderTextColor={'#B5B5B5'}
                                onChangeText={(text)=>{this.setState({card_phone:text})}}
                            />
                        </View>
                        <View style={[styles.formItem,{marginRight:15,borderBottomWidth:0}]}>
                            <Text style={[styles.leftText,{paddingRight:15}]}>验证码</Text>
                            <TextInput
                                value={this.state.code}
                                style={styles.itemRight}
                                editable = {true}
                                keyboardType={'numeric'}
                                clearButtonMode={'while-editing'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'短信验证码'}
                                placeholderTextColor={'#B5B5B5'}
                                onChangeText={(text)=>{this.setState({code:text})}}
                            />
                            <TouchableOpacity onPress={this._sendCode.bind(this)} style={styles.sendCodeBtn}>
                                <CountDownText
                                    style={styles.sendCodeText}
                                    disabledStyle={styles.disableSendCodeText}
                                    countType='seconds'
                                    ref='countDownText'
                                    afterEnd={() => {this.setState({interval:false})}}
                                    timeLeft={59}
                                    step={-1}
                                    startText='获取验证码'
                                    endText='获取验证码'
                                    auto={false}
                                    intervalText={(sec) => sec + '秒后重新获取'}
                                />
                            </TouchableOpacity>
                        </View>
                    </View>
                </KeyboardAwareScrollView>
                <View style={styles.submitBtnContainer}>
                    <Touch onPress={this._submitAction.bind(this)} style={styles.submitBtn} disable={this.state.disabled}>
                        <Text style={styles.submitBtnText}>确定</Text>
                    </Touch>
                </View>
                <ToastTip ref="toast" offsetY={160}/>
                <LoadingTip show={this.state.loadingShow}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
HkBindCard = connectHelper(state => state)(HkBindCard);

module.exports = HkBindCard;
